package com.hzx.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.hzx.entity.User;
import com.hzx.service.UserService;

@Controller
@Scope("prototype") // 多实例
public class UserAction extends BaseAction<User> {
	@Autowired
	UserService userService;

	private String checkcode;

	public String login() {

		// 获取session 验证码
		// String keyCode =
		// ServletActionContext.getRequest().getSession().getAttribute("key").toString();
		String yzm = session.get("key").toString();
		if (checkcode != null && !checkcode.isEmpty() && yzm.equals(checkcode)) {
			User user = userService.login(model.getUsername(), model.getPassword());
			if (user != null) {
				// 登录成功
				// 将用户信息放到session中
				session.put("userInfo", user);
				return HOME;
			} else {
				// 登录失败
				this.addActionError("账号或密码错误");
				return LOGIN;
			}
		} else {
			this.addActionError("验证码错误");
			return LOGIN;
		}

	}
	//退出登录
	public String logout() {
		ServletActionContext.getRequest().getSession().invalidate();
		return LOGIN;
	}
	//修改密码
	public String editPwd(){
		//获取页面提交的的密码
		String password = model.getPassword();
		//从session中拿到user
		User user = (User) session.get("userInfo");
		user.setPassword(password);
		userService.update(user);
		//向浏览器放一个数据 
		//获取response
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.print("ok");
//			response.setStatus(200);//出现时间
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//清空session跳转登录页面 重新登录
		session.clear();
 		return NONE;
		
	}
	

	public String getCheckcode() {
		return checkcode;
	}

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

}
